package com.dex4d.ui.main.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.dex4d.R;
import com.dex4d.constants.IConstants;
import com.dex4d.core.AppToolBarBaseActivity;
import com.dex4d.core.http.DefaultTransformer;
import com.dex4d.core.http.JsonApiWrapper;
import com.dex4d.core.subscribers.ProgressSubscriber;
import com.dex4d.model.HttpResult;
import com.dex4d.model.RequestParam;
import com.dex4d.model.RequestParamObj;
import com.dex4d.model.User;
import com.dex4d.ui.main.adapter.AccountAdapter;
import com.dex4d.ui.main.model.AccountCoinJson;
import com.dex4d.ui.main.model.CoinToken;
import com.dex4d.ui.main.model.HomeModel;
import com.dex4d.ui.main.model.TokenContract;
import com.dex4d.ui.main.model.TokenGame;
import com.dex4d.ui.main.socket.RPC;
import com.dex4d.utils.MoneyUtils;
import com.framework.util.DisplayUtil;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2;

/**
 * 账户页面
 */
public class AccountActivity extends AppToolBarBaseActivity {

    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout refreshLayout;

    @BindView(R.id.rv_account)
    RecyclerView recyclerView;
    AccountAdapter adapter;

    public static void start(Activity activity, HomeModel model) {
        Intent intent = new Intent(activity, AccountActivity.class);
        intent.putExtra("Top", model);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_account;
    }

    @Override
    protected void initVariables() {

        HomeModel model = getIntent().getParcelableExtra("Top");

        adapter = new AccountAdapter(this, model);
        LinearLayoutManager manager = new LinearLayoutManager(this);

        HorizontalDividerItemDecoration decoration = new HorizontalDividerItemDecoration.Builder(this)
                .color(Color.TRANSPARENT)
                .size(DisplayUtil.dip2px(this, 16))
                .visibilityProvider(adapter)
                .showLastDivider()
                .build();

        recyclerView.addItemDecoration(decoration);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                updateData(false);
            }
        });
    }

    @Override
    protected void loadData() {
        updateData(true);
    }

    @Override
    protected void initToolbar() {
        showBackView();
        String title = getResources().getString(R.string.dex4d_account_title);
        showTitle(title);
    }

    void updateData(boolean isLoading) {

        //请求此接口获取token列表
        final RequestParam requestParam2 = new RequestParam();
        requestParam2.setId(2);
        requestParam2.setJsonrpc(IConstants.JSON_RPC_VERSION);
        requestParam2.setMethod(IConstants.GATEWAY_GETTOKENTABLES);
        requestParam2.setParams(new ArrayList<String>());

        Observable<HttpResult<List<TokenContract>>> tokenTables = JsonApiWrapper
                .serviceApi()
                .getTokenTables(requestParam2);

        //获取交易信息
        final RequestParamObj requestParam = new RequestParamObj();
        requestParam.setId(2);
        requestParam.setJsonrpc(IConstants.JSON_RPC_VERSION);
        requestParam.setMethod(IConstants.GATEWAY_VAULTOVERVIEW);
        final List<RequestAccount> list = new ArrayList<>();
        list.add(new RequestAccount(User.getInstance().getAddress(), MoneyUtils.getCurrencyCode()));
        requestParam.setParams(list);

        Observable<HttpResult<AccountCoinJson>> vaultOverview = JsonApiWrapper
                .serviceApi()
                .gatewayVaultOverview(requestParam);

        Observable
                .zip(tokenTables, vaultOverview,
                        new Func2<HttpResult<List<TokenContract>>
                                , HttpResult<AccountCoinJson>
                                , List<CoinToken>>() {
                            @Override
                            public List<CoinToken> call(HttpResult<List<TokenContract>> listHttpResult
                                    , HttpResult<AccountCoinJson> result) {

                                List<CoinToken> coinTokenList = new ArrayList<>();

                                for (TokenContract temp : listHttpResult.getResult()) {
                                    if (result != null && result.getResult() != null) {
                                        AccountCoinJson coin = result.getResult();
                                        CoinToken token = coin.createCoinToken(temp.name, temp.icon_app);
                                        coinTokenList.add(token);
                                    }
                                }

                                return coinTokenList;
                            }
                        })
                .compose(new DefaultTransformer<List<CoinToken>>())  //取网络数据这个函数不能少，这是线程切换
                .subscribe(new ProgressSubscriber<List<CoinToken>>(this, isLoading) {
                    @Override
                    public void onNext(List<CoinToken> result) {
                        //更新列表数据
                        adapter.updateItemData(result);
                        refreshLayout.setRefreshing(false);
                        //请求游戏列表
//                        Observable
//                                .from(result)
//                                .concatMap(new Func1<CoinToken, Observable<HttpResult<List<TokenGame>>>>() {
//                                    @Override
//                                    public Observable<HttpResult<List<TokenGame>>> call(CoinToken coinToken) {
//                                        //请求此接口获取游戏列表
//                                        final RequestParam requestParamGame = new RequestParam();
//                                        requestParamGame.setId(1);
//                                        requestParamGame.setJsonrpc(IConstants.JSON_RPC_VERSION);
//                                        requestParamGame.setMethod(IConstants.GATEWAY_GETGAMESBYTOKENNAME);
//                                        requestParamGame.setParams(Arrays.asList(coinToken.symbol));
//                                        return JsonApiWrapper.serviceApi().getGamesByTokenName(requestParamGame);
//                                    }
//                                })
//                                .compose(new DefaultTransformer<HttpResult<List<TokenGame>>>())
//                                .subscribe(new ProgressSubscriber<HttpResult<List<TokenGame>>>(AccountActivity.this, false) {
//                                    @Override
//                                    public void onNext(HttpResult<List<TokenGame>> result) {
//                                        adapter.updateItemGame(result.getResult());
//                                    }
//                                });
                    }
                });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    public void updateUI(RPC rpc) {
        //TODO 更新订单状态
//        adapter.updatePending("eth",5);
//        adapter.updatePending("omg",3);
    }
}
